<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel="stylesheet" href="/stylesheets/style.css" />
    <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
    <script>
      // 拦截器
      axios.interceptors.request.use(
        function (config) {
          // Do something before request is sent
          console.log("请求拦截器");
          const token = localStorage.getItem("token");
          config.headers.Authorization = `Bearer ${token}`;
          return config;
        },
        function (error) {
          // Do something with request error
          return Promise.reject(error);
        }
      );

      // Add a response interceptor
      axios.interceptors.response.use(
        function (response) {
          console.log("响应拦截器");
          const { authorization } = response.headers;
          authorization && localStorage.setItem("token", authorization);
          // Any status code that lie within the range of 2xx cause this function to trigger
          // Do something with response data
          return response;
        },
        function (error) {
          // Any status codes that falls outside the range of 2xx cause this function to trigger
          // Do something with response error
          console.log(error.response.status);
          if (error.response.status === 401) {
            localStorage.removeItem("token");
            location.href = "/login";
          }
          return Promise.reject(error);
        }
      );
    </script>
    <style type="text/css">
      td img {
        width: 80px;
        height: 80px;
      }
    </style>
  </head>
  <body>
    <h1>
      后台管理-用户管理业务
      <button id="exit">退出登录</button>
    </h1>
    <div>
      <div>用户名:<input id="username" /></div>
      <div>密码:<input type="password" id="password" /></div>
      <div>年龄:<input type="number" id="age" /></div>
      <div>头像:<input type="file" id="avatar" /></div>
      <div><button id="register">添加用户</button></div>
    </div>
    <hr />
    <div>
      <button id="update">更新用户</button>
      <button id="delete">删除用户</button>
    </div>
    <hr />

    <table border="1">
      <thead>
        <tr>
          <td>头像</td>
          <td>id</td>
          <td>用户名</td>
          <td>年龄</td>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
    <script>
      var register = document.querySelector("#register");
      var exit = document.querySelector("#exit");
      var update = document.querySelector("#update");
      var deletebutton = document.querySelector("#delete");
      var username = document.querySelector("#username");
      var password = document.querySelector("#password");
      var age = document.querySelector("#age");
      var avatar = document.querySelector("#avatar");

      register.onclick = () => {
        console.log(username.value, password.value, age.value, avatar.files[0]);
        const formsdata = new FormData();
        formsdata.append("username", username.value);
        formsdata.append("password", password.value);
        formsdata.append("age", age.value);
        formsdata.append("avatar", avatar.files[0]);
        axios
          .post("/api/user", formsdata, {
            headers: {
              "Content-Type": "multipart/form-data",
            },
          })
          .then((res) => {
            console.log(res.data);
          });
      };

      update.onclick = () => {
        fetch("/api/user/669e1d8879fd38573a915dbb	", {
          method: "PUT",
          body: JSON.stringify({
            username: "xfm33",
            password: "321",
            age: 1,
          }),
          headers: {
            "Content-Type": "application/json",
          },
        })
          .then((res) => res.json())
          .then((res) => {
            console.log(res);
            if (res.ok === 0) {
              location.href = "/login";
            }
          });
      };

      deletebutton.onclick = () => {
        fetch("/api/user/66a21c3bf173327ab027bc0e	", {
          method: "DELETE",
        })
          .then((res) => res.json())
          .then((res) => {
            console.log(res);
            if (res.ok === 0) {
              location.href = "/login";
            }
          });
      };

      //获取列表
      axios.get("/api/user?page=1&limit=10").then((res) => {
        console.log(res.data);
        if (res.ok === 0) {
          location.href = "/login";
        }
        var tbody = document.querySelector("tbody");
        tbody.innerHTML = res.data
          .map(
            (item) => `
          <tr>
            <td><img src=${item.avatar}></td>  
            <td>${item._id}</td>  
            <td>${item.username}</td>  
            <td>${item.age}</td>  
          </tr>
        `
          )
          .join("");
      });

      exit.onclick = () => {
        // fetch("api/logout")
        //   .then((res) => res.json())
        //   .then((res) => {
        //     if (res.ok === 1) {
        //       location.href = "/login";
        //     }
        //   });
        localStorage.removeItem("token");
      };
    </script>
  </body>
</html>
